package com.ysg.widget.dialog;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.viewpagerindicator.CirclePageIndicator;
import com.ysg.R;
import com.ysg.base.BaseDialog;
import com.ysg.enums.NoDiamondEnum;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YRecyclerViewUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.dialog.adapter.GiftNumAdapter;
import com.ysg.widget.dialog.adapter.GiftPageAdapter;
import com.ysg.widget.dialog.entity.GiftNumResult;
import com.ysg.widget.dialog.entity.GiftListResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 礼物
 */
public class GiftDialog extends BaseDialog {
    public interface OnGiftListener{
        void onRechargeClick();
        void onSendClick(GiftListResult.GiftBean giftBean, GiftNumResult.Data giftNumEntity);
    }
    private OnGiftListener listener;
    public void setOnGiftListener(OnGiftListener listener){
        this.listener = listener;
    }

    private View parent, ll_chongzhi, ll_SendGiftNum;
    private TextView tv_GiftTypeOne, tv_GiftTypeTwo, tv_UserYE, tv_jinbiNum, tv_SendGiftNum, tv_sendFigt;
    private ViewPager mGiftPanelViewPager;
    private CirclePageIndicator circleIndicator;
    private GiftPageAdapter scrollAdapter;
    private int pageSize = 8;//每页多少条

    private GiftListResult data;
    private List<List<GiftListResult.GiftBean>> publicGiftBeans = new ArrayList<>();//公用的实体类
    private List<GiftListResult.GiftBean> giftListBeans = new ArrayList<>();
    private List<GiftListResult.GiftBean> guizuListBeans = new ArrayList<>();
    private GiftNumResult giftNumResult;
    private List<GiftNumResult.Data> giftNumList = new ArrayList<>();
    private GiftNumResult.Data giftNumEntity;

    public GiftDialog(Context context, GiftListResult data, GiftNumResult giftNumResult) {
        super(context);
        if (data != null){
            this.data = data;
            this.giftNumResult = giftNumResult;
            giftListBeans = data.getGiftList();
            guizuListBeans = data.getGuizuList();
        }
        if (giftNumResult != null){
            this.giftNumResult = giftNumResult;
            giftNumList = giftNumResult.getList();
            if (YCollectionUtil.isNotEmpty(giftNumList)){
                GiftNumResult.Data data1 = giftNumList.get(0);
                if (YStringUtil.eq(1, data1.getNum())){
                    Collections.reverse(giftNumList);
                }
            }
            giftNumEntity = giftNumList.get(giftNumList.size() - 1);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.dialog_gift;
    }

    public void initView() {
        setWidthScale(1f);
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);

        parent = findViewById(R.id.parent);
        ll_chongzhi = findViewById(R.id.ll_chongzhi);
        ll_SendGiftNum = findViewById(R.id.ll_SendGiftNum);

        tv_GiftTypeOne = findViewById(R.id.tv_GiftTypeOne);
        tv_GiftTypeTwo = findViewById(R.id.tv_GiftTypeTwo);
        tv_UserYE = findViewById(R.id.tv_UserYE);
        tv_jinbiNum = findViewById(R.id.tv_jinbiNum);
        tv_SendGiftNum = findViewById(R.id.tv_SendGiftNum);
        tv_sendFigt = findViewById(R.id.tv_sendFigt);

        setGiftViewpage();
        initPopupGiftNum();
    }

    @Override
    public void initData() {
        viewPageSetData(1);
        if (data != null){
            tv_UserYE.setText(data.getDiamonds() + "");
            tv_jinbiNum.setText(data.getJinbi() + "");
        }
    }

    @Override
    public void initListener() {
        ll_chongzhi.setOnClickListener(v -> {
            if (listener != null){
                dismiss();
                listener.onRechargeClick();
            }
        });
        ll_SendGiftNum.setOnClickListener(v -> {
            showPopupGiftNum();
        });
        tv_GiftTypeOne.setOnClickListener(v -> {
            setTabUI(1);
        });
        tv_GiftTypeTwo.setOnClickListener(v -> {
            setTabUI(2);
        });
        tv_GiftTypeTwo.setOnClickListener(v -> {
            setTabUI(2);
        });
        tv_sendFigt.setOnClickListener(v -> {
            sendGift();
        });
    }

    private void setTabUI(int tab){
        tv_GiftTypeOne.setTextColor(mContext.getResources().getColor(R.color.grayColor));
        tv_GiftTypeTwo.setTextColor(mContext.getResources().getColor(R.color.grayColor));
        switch (tab){
            case 1:
                tv_GiftTypeOne.setTextColor(mContext.getResources().getColor(R.color.white));

                break;
            case 2:
                tv_GiftTypeTwo.setTextColor(mContext.getResources().getColor(R.color.white));
                break;
        }
        viewPageSetData(tab);
    }

    /**
     * 发送礼物
     */
    private void sendGift() {
        GiftListResult.GiftBean giftBean = null;
        if (YCollectionUtil.isNotEmpty(publicGiftBeans)){
            for (List<GiftListResult.GiftBean> list: publicGiftBeans) {
                for (GiftListResult.GiftBean gift: list) {
                    if (gift.isGifItemPosition()){
                        giftBean = gift;
                        break;
                    }
                }
            }
        }

        if (giftBean == null){
            YToastUtil.showShort(R.string.dialog_gift_no_tip);
            return;
        }

        try {
            double sumMoney = Double.valueOf(data.getDiamonds());
            double giftMoney = Double.valueOf(giftBean.getGoldmoney()) * giftNumEntity.getNum();
            if (sumMoney < giftMoney){
                YToastUtil.showShort(R.string.tip_no_diamond);
                YDialogUtil.getInstance().showNoDiamond(getContext(), NoDiamondEnum.gift, true);
                dismiss();
                return;
            }
            if (listener != null){
                dismiss();
                listener.onSendClick(giftBean, giftNumEntity);
            }
        }catch (Exception e){
            YToastUtil.showShort("钻石转换错误");
        }
    }


    private void setGiftViewpage() {
        mGiftPanelViewPager = findViewById(R.id.viewpager_Gift);
        circleIndicator = findViewById(R.id.circleIndicator);
        scrollAdapter = new GiftPageAdapter(mContext);
        scrollAdapter.setMaps(publicGiftBeans);
        mGiftPanelViewPager.setAdapter(scrollAdapter);
        circleIndicator.setViewPager(mGiftPanelViewPager);
        mGiftPanelViewPager.setCurrentItem(0);
        mGiftPanelViewPager.setOffscreenPageLimit(3);

        mGiftPanelViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                scrollAdapter.notifyDataSetChanged();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /**
     * 分页设置礼物列表
     */
    private void viewPageSetData(int page) {
        publicGiftBeans.clear();
        List<GiftListResult.GiftBean> publicGiftBean = new ArrayList<>();
        switch (page) {
            case 1://礼物
                publicGiftBean.addAll(giftListBeans);
                break;
            case 2://粉丝团礼物
                publicGiftBean.addAll(guizuListBeans);
                break;
        }
        publicGiftBeans.addAll(initData(publicGiftBean));
        scrollAdapter.notifyDataSetChanged();
    }

    /**
     * 获取数据源，序列化分页
     */
    private List<List<GiftListResult.GiftBean>> initData(List<GiftListResult.GiftBean> listBeans) {
        List<GiftListResult.GiftBean> datas = new ArrayList<>();
        List<List<GiftListResult.GiftBean>> maps = new ArrayList<>();
        datas.clear();
        datas.addAll(listBeans);
        //礼物总数量如果大于8
        if (datas.size() > pageSize) {
            int pageNum = datas.size() / pageSize;
            //每页8个，计算viewpage多少页
            for (int i = 0; i < pageNum; i++) {
                int page = (i + 1) * pageSize;
                List<GiftListResult.GiftBean> PageItems = new ArrayList<>();
                PageItems.clear();
                if (i == 0) {//第一页
                    PageItems = datas.subList(i, page);
                } else {//次页....依次创建分页
                    PageItems = datas.subList(i * pageSize, page);
                }
                maps.add(PageItems);
            }
            int pageYU = datas.size() % pageSize;
            //如果总数整除8有余数，创建最后一页，剩余礼物添加到最后一页
            if (pageYU > 0) {
                List<GiftListResult.GiftBean> PageItems = new ArrayList<>();
                PageItems.clear();
                PageItems = datas.subList(datas.size() - pageYU, datas.size());
                maps.add(PageItems);
            }
        } else {
            //总数不够8个，默认只创建一页
            List<GiftListResult.GiftBean> PageItems = new ArrayList<>();
            PageItems.clear();
            PageItems = datas.subList(0, datas.size());
            maps.add(PageItems);
        }
        return maps;
    }


    /**
     * 礼物数量
     */
    private PopupWindow popupWindowGiftNum;
    private View popupGiftNum;
    private void initPopupGiftNum() {
        popupGiftNum = View.inflate(getContext(), R.layout.dialog_gift_num, null);
        RecyclerView recyclerView = popupGiftNum.findViewById(R.id.recyclerView);
        GiftNumAdapter adapter = new GiftNumAdapter();
        YRecyclerViewUtil.initNoLine(mContext, recyclerView, adapter);
        adapter.setList(giftNumList);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                GiftNumResult.Data item = giftNumList.get(position);
                tv_SendGiftNum.setText(item.getNum() + "");
                popupWindowGiftNum.dismiss();
                giftNumEntity = item;
            }
        });

        popupWindowGiftNum = new PopupWindow(popupGiftNum, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindowGiftNum.setFocusable(true);
        popupWindowGiftNum.setOutsideTouchable(true);
//        popupWindowGiftNum.setAnimationStyle(R.style.anim_menu_bottombar);
        popupWindowGiftNum.setBackgroundDrawable(new BitmapDrawable(null, ""));
    }

    private void showPopupGiftNum(){
        WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        int offset = manager.getDefaultDisplay().getWidth() / 2 - popupWindowGiftNum.getWidth() / 2;
        popupWindowGiftNum.showAtLocation(parent, Gravity.BOTTOM, offset, 0);
    }


}
